home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 1.toast / Sample Code / Java / Magic Oracle / MainFrame.java < prev    next >
Encoding:
Java Source  |  2000-09-28  |  10.1 KB  |  389 lines  |  [TEXT/SNJ2]

  1. /**
  2.  *  Apple Worldwide Developer Technical Support
  3.  *
  4.  *  "Magic Oracle" sample demonstrating AppleScript for Java.
  5.  *     User can communicate with this application via AppleScript to
  6.  *  send a question string and receive an answer string in response
  7.  *  
  8.  *  tell Application "Magic Oracle"
  9.  *       ask Oracle of Frame "oracleFrame" parameters{ "question?" }
  10.  *  end tell
  11.  *
  12.  *  by Michael Hopkins, Apple Developer Technical Support
  13.  *
  14.  *  File:   MainFrame.java
  15.  *
  16.  *  Copyright ©1999 Apple Computer, Inc.
  17.  *  All rights reserved.
  18.  *
  19.  *    4/99    v. 1.0    Shipped as 'Magic Oracle AppleScript for Java' sample.
  20.  *
  21.  *  You may incorporate this sample code into your applications without
  22.  *  restriction, though the sample code has been provided "AS IS" and the
  23.  *  responsibility for its operation is 100% yours.  However, what you are
  24.  *  not permitted to do is to redistribute the source as "Apple Sample
  25.  *  Code" after having made changes. If you're going to re-distribute the
  26.  *  source, we require that you make it clear in the source that the code
  27.  *  was descended from Apple Sample Code, but that you've made changes.
  28. **/
  29.  
  30. import BufferedImage;
  31. import BufferedDrawer;
  32. import java.awt.*;
  33. import java.awt.event.*;
  34.  
  35. /**
  36.  * A class by the Magic Oracle application that is a simple extension of the 
  37.  * java.awt.Frame class. It contains all the elements necessary to act as the
  38.  * main window of an application.
  39.  * @version 1.0, April 9, 1999
  40.  * @author Michael Hopkins, Worldwide Developer Technical Support, Apple Computer Inc.
  41.  **/
  42. public class MainFrame extends Frame
  43. {
  44.     /**
  45.       * Default constructor
  46.       **/
  47.     public MainFrame()
  48.     {
  49.         setLayout(new BorderLayout(0,0));
  50.         setVisible(false);
  51.         setSize(477,418);
  52.         setBackground(new Color(12632256));
  53.         
  54.         panel1 = new java.awt.Panel();
  55.         panel1.setLayout(null);
  56.         panel1.setBounds(0,388,477,30);
  57.         add("South", panel1);
  58.         
  59.         button1 = new java.awt.Button();
  60.         button1.setLabel("Ask the Oracle");
  61.         button1.setBounds(212,3,100,23);
  62.         panel1.add(button1);
  63.         
  64.         textField1 = new java.awt.TextField();
  65.         textField1.setText("What is thy Bidding?");
  66.         textField1.setBounds(18,3,183,26);
  67.         textField1.setForeground(new Color(0));
  68.         textField1.setBackground(new Color(16777215));
  69.         panel1.add(textField1);
  70.         
  71.         bufferedImage1 = new BufferedImage();
  72.         bufferedImage1.setBounds(0,0,477,388);
  73.         bufferedImage1.setBackground(new Color(16777215));
  74.         add("Center", bufferedImage1);
  75.         
  76.         setTitle("Ask the Oracle");
  77.         this.setName("oracleFrame");    /**
  78.                                           * by calling setName(), we can refer to our frame as
  79.                                          * Frame "oracleFrame" in AppleScript instead of Frame 1
  80.                                          */
  81.         
  82.         SymWindow aSymWindow = new SymWindow();
  83.         this.addWindowListener(aSymWindow);
  84.         SymMouse aSymMouse = new SymMouse();
  85.         bufferedImage1.addMouseListener(aSymMouse);
  86.         SymMouseMotion aSymMouseMotion = new SymMouseMotion();
  87.         bufferedImage1.addMouseMotionListener(aSymMouseMotion);
  88.         SymAction lSymAction = new SymAction();
  89.         button1.addActionListener(lSymAction);
  90.         textField1.addActionListener(lSymAction);
  91.         
  92.         userInit();
  93.     }
  94.  
  95.     static public void main(String args[])
  96.     {
  97.         (new MainFrame()).setVisible(true);
  98.     }
  99.     
  100. /**
  101.  * UserInit 
  102.  * Loads neccessary images and prepares offscreen graphics areas
  103.  **/
  104.     protected void userInit()
  105.     {
  106.         String imagePath = "images/Ball.jpg";
  107.         ballimage = Util.loadImage(imagePath, this);
  108.         if (ballimage == null)
  109.         {
  110.             System.err.println("Could not load image \"" + imagePath + "\"");
  111.         }
  112.         else
  113.         {
  114.             bufferedImage1.setImage(ballimage);
  115.         }
  116.         String image = "image";
  117.         String jpg   = ".jpg";
  118.         images = new Image[24];
  119.         for ( int i = 0; i < 24; i++ )
  120.         {
  121.             imagePath = "images/" + image + (i+1) + jpg;
  122.             images[i] = Util.loadImage( imagePath, this);
  123.             if (images[i] == null)
  124.             {
  125.                 System.err.println("Could not load image \"" + imagePath + "\"");
  126.             }    
  127.         }
  128.     }
  129.         
  130.     /**
  131.      * Shows or hides the component depending on the boolean flag b.
  132.      * @param b  if true, show the component; otherwise, hide the component.
  133.      * @see java.awt.Component#isVisible
  134.      */
  135.     public void setVisible(boolean b)
  136.     {
  137.         if(b)
  138.         {
  139.             setLocation(50, 50);
  140.         }    
  141.         super.setVisible(b);
  142.     }
  143.     
  144.  
  145.     java.awt.Panel panel1;
  146.     java.awt.Button button1;
  147.     java.awt.TextField textField1;
  148.     BufferedImage bufferedImage1;
  149.  
  150.     
  151.     protected Image ballimage;
  152.     protected Image images[];
  153.     protected boolean dragging = false;
  154.     protected Point startPoint;
  155.     protected Fortune oracle = new Fortune();
  156.  
  157.     /**
  158.      * Handle window events
  159.      */
  160.      class SymWindow extends java.awt.event.WindowAdapter
  161.     {
  162.         public void windowClosing(java.awt.event.WindowEvent event)
  163.         {
  164.             Object object = event.getSource();
  165.             if (object == MainFrame.this)
  166.                 MainFrame_WindowClosing(event);
  167.         }
  168.     }
  169.     
  170.     void MainFrame_WindowClosing(java.awt.event.WindowEvent event)
  171.     {
  172.         setVisible(false);    // hide the Frame
  173.         dispose();            // free the system resources
  174.         System.exit(0);        // close the application
  175.     }
  176.     
  177.     /**
  178.      * Inner class for handling mouse events
  179.      */
  180.     class SymMouse extends java.awt.event.MouseAdapter
  181.     {
  182.        /**
  183.          * Handle mousePressed events
  184.          */
  185.         public void mousePressed(java.awt.event.MouseEvent event)
  186.         {
  187.             Object object = event.getSource();
  188.             if (object == bufferedImage1)
  189.             {
  190.                 bufferedImage1_MousePressed(event);
  191.                 dragging = false;
  192.             }
  193.         }
  194.     
  195.        /**
  196.          * Handle mouseReleased events
  197.          */
  198.         public void mouseReleased(java.awt.event.MouseEvent event)
  199.         {
  200.             Object object = event.getSource();
  201.             if (object == bufferedImage1)
  202.                 bufferedImage1_MouseReleased(event);
  203.             if ( dragging == true )    // user must drag the ball. Clicking on it will not invoke it
  204.             {
  205.                 askMystic( textField1.getText() );
  206.             }
  207.         }
  208.     }
  209.  
  210.     /**
  211.      * Handle mouseDragged events
  212.      */
  213.     class SymMouseMotion extends java.awt.event.MouseMotionAdapter
  214.     {
  215.         public void mouseDragged(java.awt.event.MouseEvent event)
  216.         {
  217.             Object object = event.getSource();
  218.             if (object == bufferedImage1)
  219.             {
  220.                 bufferedImage1_MouseDragged(event);
  221.                 dragging = true;
  222.             }
  223.         }
  224.     }
  225.     
  226.     /**
  227.      * Factored routine exposed to AppleScript that performs the oracle "magic"
  228.      * @param question Query to ask of the oracle
  229.      * @return reponse from oracle
  230.      */
  231.     public String askMystic( String question )
  232.     {
  233.         if ( !(textField1.getText().equals( question )))
  234.             textField1.setText( question );
  235.         
  236.         String s = "";
  237.         if ( question.equals( "" ))    // if no question is asked, return a canned response
  238.         {
  239.             animateTriangle( false );
  240.             s = "Please ask a question";
  241.         }    
  242.         else                        // if there is a question, clear textfield and generate response
  243.         {
  244.             animateTriangle( );
  245.             s = oracle.getResponse();
  246.             try
  247.             {
  248.                 Thread.sleep(150);    // delay in between frames of animation
  249.             }
  250.             catch (InterruptedException exc) { }
  251.             textField1.setText("");
  252.         }
  253.         return s;
  254.     }
  255.  
  256.     
  257.     
  258.     /**
  259.      * Perform animation of floating dodecahedron 
  260.      * @param input true if non-empty input from textfield
  261.      */
  262.     void animateTriangle( boolean input )
  263.     {
  264.         Graphics g = getGraphics();
  265.         Point origin = new Point(bufferedImage1.getImageLocation()); 
  266.         origin.x += 114;        // upper left corner for drawing repsonse images
  267.         origin.y += 112;
  268.         if ( g != null )
  269.         {
  270.             for ( int i = 0; i < 3; i++ )
  271.             {
  272.                 try
  273.                 {
  274.                     Thread.sleep(150);    // delay in between frames of animation
  275.                 }
  276.                 catch (InterruptedException exc) { }
  277.                 g.drawImage( images[i], origin.x, origin.y, this );    // draw 3 common animation frames
  278.             }
  279.             try
  280.             {
  281.                 Thread.sleep(150);
  282.             }
  283.             catch (InterruptedException exc) { }
  284.             if ( input )
  285.                 g.drawImage( images[oracle.generateResponseNum() + 4], origin.x, origin.y, this ); // draw response frame
  286.             else
  287.                 g.drawImage( images[3], origin.x, origin.y, this );    // draw "Ask A ?"
  288.         }
  289.     }
  290.     
  291.     /**
  292.      * Perform animation of floating dodecahedron 
  293.      * This routine simulates calling this routine with a default value of true
  294.      */
  295.     void animateTriangle( )
  296.     {
  297.         animateTriangle( true );
  298.     }
  299.     
  300.     /**
  301.      * Handles mouse pressed events in the buffered image
  302.      */
  303.     void bufferedImage1_MousePressed(java.awt.event.MouseEvent event)
  304.     {
  305.         Point eLoc = event.getPoint();                    // cache click location
  306.         Point iLoc = bufferedImage1.getImageLocation(); // cache image location
  307.         Dimension iSize = bufferedImage1.getImageSize();
  308.         Rectangle imageRect = new Rectangle(iLoc.x, iLoc.y, iSize.width, iSize.height);
  309.         if (imageRect.contains(eLoc))                    // determine if click was within image
  310.         {
  311.             startPoint = new Point(eLoc.x - iLoc.x, eLoc.y - iLoc.y);
  312.         }
  313.         else
  314.             startPoint = null;
  315.     }
  316.  
  317.     /**
  318.      * Handles mouse dragged events in the buffered image
  319.      */
  320.     void bufferedImage1_MouseDragged(java.awt.event.MouseEvent event)
  321.     {
  322.         if (startPoint != null)        // gets the location of the image, offsets it and draws
  323.         {
  324.             Point eLoc = event.getPoint();
  325.             eLoc.translate(-startPoint.x, -startPoint.y);
  326.             bufferedImage1.setImageLocation(eLoc);
  327.             bufferedImage1.paint(getGraphics());
  328.         }
  329.     }
  330.     
  331.     /**
  332.      * resets the startPoint of the buffered image when the mouse button is released
  333.      */
  334.     void bufferedImage1_MouseReleased(java.awt.event.MouseEvent event)
  335.     {
  336.         startPoint = null;
  337.     }
  338.  
  339.     /**
  340.      * Respond to button clicks and enter key pressed in text field
  341.      */
  342.     class SymAction implements java.awt.event.ActionListener
  343.     {
  344.         public void actionPerformed(java.awt.event.ActionEvent event)
  345.         {
  346.             Object object = event.getSource();
  347.             if (object == button1)
  348.                 button1_ActionPerformed(event);
  349.             else if (object == textField1)
  350.                 textField1_EnterHit(event);
  351.         }
  352.     }
  353.  
  354.     /**
  355.      * Respond to "Ask Mystic" button pressed event
  356.      */
  357.     void button1_ActionPerformed(java.awt.event.ActionEvent event)
  358.     {
  359.         askMystic( textField1.getText( ));
  360.     }
  361.  
  362.     /**
  363.      * Respond enter key pressed in textfield
  364.      */
  365.     void textField1_EnterHit(java.awt.event.ActionEvent event)
  366.     {
  367.         simulateClick(button1);
  368.     }
  369.  
  370.     /**
  371.      * A function to simulate a click on the target button.
  372.      * This will make the button draw as if it had been pressed and
  373.      * released, and the button will fire an Action event as if
  374.      * the button were pressed.
  375.      * For use with the Apple MRJ 2.1 EA3 and later.
  376.      */
  377.     static protected void simulateClick(Button target)
  378.     {
  379.         if (target != null)
  380.         {
  381.             KeyEvent keyEvent = new KeyEvent(target, KeyEvent.KEY_PRESSED, 
  382.                                            System.currentTimeMillis(), 0, KeyEvent.VK_ENTER, 
  383.                                            (char)KeyEvent.VK_ENTER);
  384.             target.dispatchEvent(keyEvent);
  385.         }
  386.     }
  387. }
  388.  
  389.